'use client'

import { Typography } from '@mui/material'
import Box from '@mui/material/Box'
import { keepPreviousData, useQuery } from '@tanstack/react-query'
import { type MRT_ColumnDef } from 'material-react-table'
import { useRouter } from 'next/navigation'
import { useEffect, useMemo } from 'react'

import { Table } from '@/components/Table'

import {
	type IRequest,
	type IRequests,
	requestsColumns
} from '@/types/request.types'

import { DASHBOARD_PAGES } from '@/config/pages-url.config'

import { requestService } from '@/services/requests.service'

export const Requests = () => {
	const {
		data, //your data and api response will probably be different
		isError,
		isRefetching,
		isLoading,
		refetch,
		error
	} = useQuery<IRequests>({
		queryKey: ['requests'],
		queryFn: async () => await requestService.fetchMany(),
		placeholderData: keepPreviousData //don't go to 0 rows when refetching or paginating to next page
	})

	const { push } = useRouter()

	const columns = useMemo<MRT_ColumnDef<IRequest>[]>(() => requestsColumns, [])

	return (
		<Table
			columns={columns}
			count={data?.count ?? 0}
			data={data?.results ?? []}
			initSorting={[{ id: 'id', desc: false }]}
			isError={isError}
			isLoading={isLoading}
			isRefetching={isRefetching}
			refetch={refetch}
			defaultPinnedColumns={['id', 'first_name']}
			handleView={id => push(`${DASHBOARD_PAGES.REQUEST}/${id}`)}
			createBtn={{
				label: 'Создать новую',
				action: () => push(DASHBOARD_PAGES.REQUEST_NEW)
			}}
			enableExpandAll={false}
			renderDetailPanel={({ row }) => (
				<Box>
					<Typography variant={'h6'}>Номер в ПО:</Typography>
					<Typography
						sx={{
							paddingBottom: 2,
							whiteSpace: 'pre-line'
						}}
					>
						{row.original.number_in_program.length
							? row.original.number_in_program
							: 'Не указан'}
					</Typography>

					<Typography variant={'h6'}>Заметка:</Typography>
					<Typography
						sx={{
							paddingBottom: 2,
							whiteSpace: 'pre-line'
						}}
					>
						{row.original.note.length ? row.original.note : '-'}
					</Typography>

					<Typography variant={'h6'}>История изменений:</Typography>
					<Typography>
						{row.original.changes_history.length
							? row.original.changes_history
							: '-'}
					</Typography>
				</Box>
			)}
		/>
	)
}
